package com.tb.shiro.realms;

import com.tb.mapper.RoleMapper;
import com.tb.mapper.UserMapper;
import com.tb.pojo.Permission;
import com.tb.pojo.Role;
import com.tb.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper um;

    @Autowired
    private RoleMapper rm;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //授权
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
//        System.out.println("进入授权");
        User user = um.findUser2RoleById(primaryPrincipal);
        if (user != null) {
            Set<String> roleSet = new HashSet<>();
            Set<String> permissionSet = new HashSet<>();
            for (Role role : user.getRoleList()) {
                for (Permission permission : rm.findRole2PerByUsername(role.getRole()).getPermissionList()) {
                    permissionSet.add(permission.getPermission());
//                    System.out.println(role.getRole() + "-->" + permission.getPermission());
                }
                roleSet.add(role.getRole());
            }
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roleSet);
            simpleAuthorizationInfo.setStringPermissions(permissionSet);

            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String)token.getPrincipal();
//        UserMapper um = (UserMapper) SpringUtils.getBean("userMapper");
        User user = um.login(principal, null);
        if (user != null) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }


}
